<template>
  <div>

    <el-dialog title="导入员工" width="40%" :visible.sync="importFlag">
      <div class="import-user">
        <el-upload
          class="upload-demo"
          drag
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-change="handleChange"
          multiple
        >
          <i class="el-icon-upload" />
          <div><el-link type="primary" @click.stop="downLoadUser">点击下载模版</el-link></div>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="importFlag=false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getExportTemplate, importUser } from '@/api/personnel'
import { saveAs } from 'file-saver'
export default {
  data() {
    return {
      importFlag: false // 显示隐藏的flag
    }
  },
  methods: {
    async  downLoadUser() { // 下载员工导入模版
      const res = await getExportTemplate()
      console.log(res, '二进制文件')
      saveAs(res, '员工导出模版.xlsx')
    },
    async  handleChange(file) { // 导入员工接口
      console.log(file.raw)// file.raw elementui 上传插件选择的文件
      const formdata = new FormData()
      // "content-type": "multipart/form-data"    文件类型
      //  "content-type": "application/json"               {name:1,age:2}
      //  "content-type": "application/x-www-form-urlencoded"  name=1&age=2
      //  formdata.append(随机key,文件对象)
      formdata.append('file', file.raw)
      // 导入员工接口
      const res = await importUser(formdata)
      console.log(res)
      this.$message.success('导入成功')

      // 出发eventBus事件 跳转最后一页
      this.$bus.$emit('importUserSuccess')
      this.importFlag = false
    }
  }
}
</script>
<style lang="scss">
  .import-user{
    width: 100%;
    padding: 30px;
    box-sizing:border-box;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
